package part14threadcommunication;

/**
 * @description: 测试生产消费模型-->利用缓冲区解决-->管程法
 * 生产者，消费者，产品，缓冲区
 * @author: zhang hang
 * @date: 2022/10/7 11:39.
 * @version: 1.0
 */
public class TestPC {

    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Producer(container).start();
        new Consumer(container).start();
    }

}

/**
 * description: 生产者
 **/
class Producer extends Thread {
    SynContainer container;

    public Producer(SynContainer container) {
        this.container = container;
    }

    // 生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了第" + i + "只鸡");
        }
    }
}

/**
 * description: 消费者
 **/
class Consumer extends Thread {
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }

    // 消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了第" + container.pop().id + "只鸡");
        }
    }


}

/**
 * description: 产品
 **/
class Chicken {
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

/**
 * description: 缓冲区
 **/
class SynContainer {

    Chicken[] chickens = new Chicken[10];
    int count = 0;

    public synchronized void push(Chicken chicken) {
        if (count == chickens.length) {
            // 生产者等待，通知消费者消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[count] = chicken;
        count++;
        // 通知消费者消费
        this.notifyAll();
    }

    public synchronized Chicken pop() {
        if (count == 0) {
            // 消费者等待，等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];
        // 通知生产者生产
        this.notifyAll();
        return chicken;
    }


}
